使用 Go-micro 构建微服务-2 gRPC 配置中心服务
January / 1 / 2020
概览
本章将演示实现一个 gRPC 配置中心服务端及客户端调用
包含内容
gRPC 配置中心示例
不包含内容
负载均衡
准备工作
Redis (optional)
docker-compose.yaml
Go 1.13
The only change you have to make is add a dot to the first element of the module path. If you don't intend to make the module available on the internet, you can use a reserved TLD like
.localhost
that signifies that. For example, the following module path would work:my-api-server.localhost/my-utils/uuid
ref:https://github.com/golang/go/issues/35020
在 go1.13 中, go module 名称规范要求路径的第一部分必须满足域名规范,否则会报malformed module path "XXXXXX": missing dot in first path element
我们的解决方案
STEP 1: 重命名目录
mv Go-mini-kit go-mini-kit.com
STEP 2: go.mod 中使用 replace
源码
https://github.com/WenyXu/Go-mini-kit/tree/Part2 业务代码非常简单,在此不再赘述。
config-grpc-srv
我们使用 micro/go-micro 生态内 micro/go-plugins 下 config/source/grpc 来实现一个 gRPC 服务 micro/go-plugins/config/source/grpc 目录结构
grpc.proto
github.com/micro/go-plugins/config/source/grpc/proto/grpc.proto
服务端 main.go 实现
回到我们的目录实现这个 gRPC 服务的 Read & Watch func config-grpc-srv 目录结构
user-srv
在 user-srv 调用 gRPC Client
user-srv/main.go
grpc.go
github.com/micro/go-plugins/config/source/grpc/grpc.go
user-srv/main.go 中调用 NewSource 返回一个 grpcSource struct (实现了 source.Source interface )
grpc/grpc.go 中 grpcSource Read & Watch 调用 gRPC client 发起请求
再来关注到 user-srv/main.go (文中)Line 16 boot.Init(config.WithSource(source))
boot/boot.go Init func
boot/config.go Init funct
boot/config.go func (c *configurator) init(options Options) (err error)
这里我们再来看看到 boot/config.go func (c *configurator) init(options Options) (err error) (上文)Line 10 config.NewConfig() NewConfig() 返回了 Config interface
go-micro/config/config/config.go func NewConfig(opts ...Option) Config
go-micro/config/config/config.go type Config interface
go-micro/config/config/default.go func newConfig(opts ...Option) Config
go-micro/config/config/default.go type config struct
go-micro/config/config/default.go func (c *config) Load(sources ...source.Source) error
这里 c.opts.Loader 即 memory.NewLoader() 返回实现了 loader.Loader interface 的对象
go-micro/config/loader/loader.go type Loader interface
memory struct 实现了 loader.Loader interface go-micro/config/loader/memory func (m *memory) Load(sources ...source.Source) error
Line 7 source.Read()
还记得我们最开始 grpcSource struct (实现了 source.Source interface)吗?我们在 user-srv/main.go 创建 grpcSource (实现了 source.Source interface) 被传入到 config.Load(source ...source.Source) 中,然后在 Load() 中调用实现 source.Source interface 对象的 Read() ,这个 Read() 便是正是 grpc/grpc.go 中实现的。
grpc/grpc.go func (g grpcSource) Read() (set source.ChangeSet, err error)
boot
boot/config.go
至此所有流程都梳理完了 boot/config.go